package ui20131001.service
{
	import baidu.map.basetype.LngLat;
	import baidu.map.event.ConvertEvent;
	import baidu.map.service.convert.ConvertType;
	import baidu.map.service.convert.Convertor;
	
	import flash.display.DisplayObjectContainer;
	
	import mx.controls.Alert;
	
	import ui20131001.bMapHelper.BMapHelper;

	/**
	 * @author : LIMIN
	 * @time : 2014-2-8 上午10:33:56
	 * 
	 * @remarks :
	 */
	
	public class ConvertorCommand
	{
		public static var isDoing:Boolean;
		protected var _callback:Function;
		private var _points:Array;//分割后的点数组
		private var _returnPoints:Array;//返回后的点数组
		
		public function ConvertorCommand(callback:Function)
		{
			_callback = callback;
		}
		
		/**
		 * @param arr [new Point(x, y), ...]
		 */
		public function execute(arr:Array):void
		{
			//注意，一次只能转换20个点
			if(!isDoing)
			{
				isDoing = true;
				addEvent();
//				con.convert(point.lng, point.lat, ConvertType.GCJ02_TO_BAIDU);
				
				//处理arr，要分割成20一组
				_points = [];
				var startIdx:int = 0;
				var endIdx:int = arr.length;
				var aa:Array;
				while(startIdx<endIdx)
				{
					aa = arr.slice(startIdx, startIdx+20);
					_points.push(aa);
					startIdx += 20;
				}
				
				_returnPoints = [];
				doConvert(_points.shift());
			}
		}
		
		private function doConvert(arr:Array):void
		{
			con.batConvert(arr, ConvertType.GCJ02_TO_BAIDU);
		}
		
		private function get con():Convertor
		{
			return BMapHelper.getInst().convertor;
		}
		
		private function addEvent():void
		{
//			con.addEventListener(ConvertEvent.CONVERT_SUCCESS, successHandler);
			con.addEventListener(ConvertEvent.BAT_CONVERT_COMPLETE, successHandler);
			con.addEventListener(ConvertEvent.CONVERT_FAIL, failHandler);
			con.addEventListener(ConvertEvent.NETWORK_ERROR, failHandler);
		}
		private function removeEvent():void
		{
//			con.removeEventListener(ConvertEvent.CONVERT_SUCCESS, successHandler);
			con.removeEventListener(ConvertEvent.BAT_CONVERT_COMPLETE, successHandler);
			con.removeEventListener(ConvertEvent.CONVERT_FAIL, failHandler);
			con.removeEventListener(ConvertEvent.NETWORK_ERROR, failHandler);
		}
		
		private function successHandler(e:ConvertEvent):void
		{
			var arr:Array = e.data;
			_returnPoints = _returnPoints.concat(arr);
			
			if(_points.length>0)
			{
				doConvert(_points.shift());
			}else
			{
				isDoing = false;
				removeEvent();
				Global.hideLoading();
				_callback(_returnPoints);
			}
		}
		
		private function failHandler(e:ConvertEvent):void
		{
			isDoing = false;
			removeEvent();
			Global.hideLoading();
			Alert.show('坐标转换出错', '百度地图错误');
		}
		
	}
}